#include <string.h>
#include <stdio.h>
#include <stdlib.h>

// 
char myenv[1024];

#define MAX_SIZE 1024
#define ARGV_SIZE 32
#define DELIM " \t"

char* argv[ARGV_SIZE];


int main() {
    // 创建一个新的环境变量字符串
    char newEnvVar[] = "NEW_ENV_VAR=HelloWorld";

    // 将新的环境变量添加到程序的环境变量表中
    if (putenv(newEnvVar) != 0) {
        perror("putenv failed");
        return EXIT_FAILURE;
    }

    // 验证环境变量是否已成功添加
    char *value = getenv("NEW_ENV_VAR");
    if (value != NULL) {
        printf("NEW_ENV_VAR is set to: %s\n", value);
    } else {
        printf("NEW_ENV_VAR is not set.\n");
    }

    // 创建一个子进程来检查环境变量是否已传递
    pid_t pid = fork();
    if (pid == 0) { // 子进程
        // 在子进程中再次检查环境变量
        value = getenv("NEW_ENV_VAR");
        if (value != NULL) {
            printf("In child process, NEW_ENV_VAR is set to: %s\n", value);
        } else {
            printf("In child process, NEW_ENV_VAR is not set.\n");
        }
        exit(EXIT_SUCCESS);
    } else if (pid < 0) { // fork失败
        perror("fork failed");
        return EXIT_FAILURE;
    } else { // 父进程
        // 等待子进程结束
        wait(NULL);
    }

    return 0;
}














/*
int main()
{
    char str[MAX_SIZE];
    printf("sizeof(str): %d\n",sizeof(str));
    fgets(str,sizeof(str),stdin);
    printf("sizeof(str): %d\n",sizeof(str));

    int i = 0;
    argv[i++] = strtok(str, DELIM);
    while(argv[i++] = strtok(NULL, DELIM));
    
    for(i=0; argv[i];++i)
    {
        printf("%d: %s\n",i, argv[i]);
    }
    if(strcmp(argv[0],"export")==0)
    {
        if (putenv(argv[1]) != 0) {
            perror("putenv failed");
            return EXIT_FAILURE;
        }
        char *value = getenv("NEW_ENV_VAR");
    if (value != NULL) {
        printf("NEW_ENV_VAR is set to: %s\n", value);
    } else {
        printf("NEW_ENV_VAR is not set.\n");
    }

    }

    return 0;
}
*/

/*
int main(int argc, char* argv[], char* env[])
{
    int i = 0;
    for(; env[i]; ++i)
    {
        printf("%d: %s\n",i, env[i]);
    }
    printf("========================\n");
    // getenv
    // 获取环境变量
    char* s = getenv("PATH"); 
    printf("s: %s\n",s);

    // putenv
    // 添加环境变量
    char* put = "MY_VAL=111111";
    strcpy(myenv, put);
    putenv(myenv);

    return 0;
}

*/
